# Example ： re 正则表达式模块
# ip地址正则匹配对象
# re_obj = re.compile('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
# 判断ip出现次数，返回字典
def count_log(file, re_str):
    re_obj = re.compile(re_str)
    with open(file, mode='r') as fr:
        mydict = {}
        for line in fr.readlines():
            # print(line)
            ip = re_obj.search(line).group()
            # print(ip.group())
            if ip not in mydict:
                mydict[ip] = 1
            else:
                mydict[ip] += 1
    return mydict

if __name__ == '__main__':
    ip_str = re.compile('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')
    print(count_log('apache_log.txt', ip_str))
    host_str